<template>
	<div class="editBox clearfix" ref='editmain'>
		<quill-editor class="editor" ref="myQuillEditor" :content="content" @change="onEditorChange($event)" :options="editorOption">
		</quill-editor>
		<div v-show="false">
			<input ref='uploadbtnImage' class="uploadbtnImage" type="file" accept=".jpg,.png,.JPG,.PNG" style="display: none" @change="editorUploadImage($event)" />
			<input ref='uploadbtnVideo' class="uploadbtnVideo" type="file" accept=".mp4,.MP4" style="display: none" @change="editorUploadVideo($event)" />
		</div>
	</div>
</template>

<script>
	import { putProgress } from "@/utils/oss.js";
	export default {
		props: {
			content: {
				type: String,
				required: false,
				default: ''
			},
		},
		data() {
			return {
				editorOption: {
					autoFocus: false,
					modules: {
						imageResize: {
							displayStyles: {
								backgroundColor: 'black',
								border: 'none',
								color: 'white'
							},
							modules: ['Resize']
						},
						toolbar: [
							['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
							[{
								'header': [1, 2, 3, 4, 5, 6, false]
							}], //几级标题
							[{
								"size": ["12px", "14px", "16px", "18px", "20px", "22px", "24px", "26px", "28px", "30px", "32px", "34px"]
							}], // 字体大小
							[{
								'align': []
							}], //对齐方式
							['image', 'video'],
							[{
								'indent': '-1'
							}, {
								'indent': '+1'
							}], // 缩进
							[{
								'list': 'ordered'
							}, {
								'list': 'bullet'
							}], //列表
							['clean'], //清除字体样式
							[{
								'color': []
							}, {
								'background': []
							}],
						]
					},
					placeholder: '请输入正文',
				},
			}
		},
		mounted() {
			this.editorUpload()
		},
		methods: {
			onEditorChange(data) {
				this.$emit('change', data)
			},
			getUUID() {
				return  'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
					let  r = Math.random() * 16 | 0,
						v = c ==  'x'  ? r : (r & 0x3 | 0x8);
					return  v.toString(16);    
				});
			},
			editorUpload() {
				let that = this;
				this.$nextTick(() => {
					let myQuillEditor = this.$refs.myQuillEditor;
					let imgHandler = async function(image) {
						that.addImgRange = that.$refs.myQuillEditor.quill.getSelection();
						if(image) {
							that.$refs.uploadbtnImage.click()
						}
					}
					this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", imgHandler);
					let videoHandler = async function(image) {
						that.addImgRange = that.$refs.myQuillEditor.quill.getSelection();
						if(image) {
							that.$refs.uploadbtnVideo.click()
						}
					}
					this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("video", videoHandler);

					const titleConfig = {
						'ql-bold': '加粗',
						'ql-color': '颜色',
						'ql-font': '字体',
						'ql-code': '插入代码',
						'ql-italic': '斜体',
						'ql-link': '添加链接',
						'ql-background': '背景颜色',
						'ql-size': '字体大小',
						'ql-strike': '删除线',
						'ql-script': '上标/下标',
						'ql-underline': '下划线',
						'ql-blockquote': '引用',
						'ql-header': '标题',
						'ql-indent': '缩进',
						'ql-list': '列表',
						'ql-align': '文本对齐',
						'ql-direction': '文本方向',
						'ql-code-block': '代码块',
						'ql-formula': '公式',
						'ql-image': '图片',
						'ql-video': '视频',
						'ql-clean': '清除字体样式'
					}
					const oToolBar = that.$refs.editmain.querySelector('.ql-toolbar'),
						aButton = oToolBar.querySelectorAll('button'),
						aSelect = oToolBar.querySelectorAll('select');
					aButton.forEach(function(item) {
						if(item.className === 'ql-script') {
							item.value === 'sub' ? item.title = '下标' : item.title = '上标'
						} else if(item.className === 'ql-indent') {
							item.value === '+1' ? item.title = '向右缩进' : item.title = '向左缩进'
						} else {
							if(item.value === "ordered") {
								item.title = '有序列表'
							} else if(item.value === "bullet") {
								item.title = '无序列表'
							} else {
								item.title = titleConfig[item.classList[0]]
							}
						}
					})
					aSelect.forEach(function(item) {
						item.parentNode.title = titleConfig[item.classList[0]]
					})
				})
			},
			editorUploadImage(event) {
				let that = this;
				const files = event.target.files;
				if(!files || files.length <= 0) {
					return;
				}
				const file = files[0];
				let filetype = file.name.substring(file.name.lastIndexOf('.') + 1);
				if(filetype != 'jpg' && filetype != 'png' && filetype != 'JPG' && filetype != 'PNG') {
					this.$message({
						type: 'error',
						message: '请上传jpg或png格式的图片！'
					})
					return
				}
				const key = `szhjxpt/editor/images/${this.getUUID()}/${file.name}`;
				putProgress(key, file).then(res => {
					let value = this.baseurl + key;
					that.addImgRange = that.$refs.myQuillEditor.quill.getSelection()
					that.$refs.myQuillEditor.quill.insertEmbed(that.addImgRange != null ? that.addImgRange.index : 0, 'image', value, null)
					that.$refs.uploadbtnImage.value = '';
				});
			},
			editorUploadVideo(event) {
				let that = this;
				const files = event.target.files;
				if(!files || files.length <= 0) {
					return;
				}
				const file = files[0];
				let filetype = file.name.substring(file.name.lastIndexOf('.') + 1);
				if(filetype != 'mp4' && filetype != 'MP4') {
					this.$message({
						type: 'error',
						message: '请上传mp4格式的视频！'
					})
					return
				}
				const key = `szhjxpt/editor/videos/${this.getUUID()}/${file.name}`;
				putProgress(key, file).then(res => {
					let value = this.baseurl + key;
					that.addImgRange = that.$refs.myQuillEditor.quill.getSelection()
					that.$refs.myQuillEditor.quill.insertEmbed(that.addImgRange != null ? that.addImgRange.index : 0, 'video', value, null)
					that.$refs.uploadbtnVideo.value = '';
				});
			},
		}
	}
</script>

<style scoped>
	.editBox {
		width: 100%;
		height: auto;
	}
</style>